package com.fc.backingbeans.recipe;

import javax.faces.bean.ViewScoped

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

import com.fc.entities.Recipe
import com.fc.service.RecipeService
import com.fc.service.UserDetailsService
import com.fc.service.exceptions.FCException
import com.fc.utils.MessageUtils

/**
 * 
 * @author Ács Ádám
 *
 */
@Component("recipeTableController")
@ViewScoped
class RecipeTableController implements Serializable {
	@Autowired private RecipeService recipeService
	@Autowired private AddRecipeDialog addRecipeDialog
	@Autowired private RecipeController recipeController
	@Autowired private UserDetailsService userService

	private List<Recipe> filtered
	private List<Recipe> recipes
	private Recipe selected

	boolean needRefresh

	List<Recipe> getFiltered() {
		return filtered;
	}

	void setFiltered(List<Recipe> filtered) {
		this.filtered = filtered;
	}

	List<Recipe> getRecipes() {
		if (recipes == null || needRefresh) {
			recipes = recipeService.findAllByUser(userService.currentUser);
			needRefresh = false;
		}

		return recipes;
	}

	void delete(Recipe recipe) {
		try {
			recipeService.delete(recipe);
		} catch (FCException fcex) {
			MessageUtils.addError("Sikertelen törlés", fcex.getMessage());
		} catch (Exception ex) {
			MessageUtils.addError("Sikertelen törlés", "");
		}
	}

	void requestRefresh() {
		needRefresh = true
	}

	Recipe getSelected() {
		return selected;
	}

	void setSelected(Recipe selected) {
		this.selected = selected
		recipeController.recipe = selected
	}
}
